package com.zkingsoft.actions.common.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zkingsoft.constance.Dictionary;
/**
 * 上传文件工具类
 * @Title: UploadUtils.java  
 * @Package com.zkingsoft.actions.common.upload  
 * @description 
 * @author 罗凯
 * @email 18075895212@qq.com
 * @date  2016年11月13日 上午9:55:47
 */
public class UploadUtils {
	//文件保存目录路径
	String savePath = Dictionary.SAVE_PATH;

	//文件保存目录URL
	String saveUrl  = Dictionary.SAVE_URL;
	
	//定义文件上传的类型及限制类型
	public static HashMap<String, String> extMap = new HashMap<String, String>();
	static{
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
	}
	//定义最大文件大小
	long maxSize =1024* 1024*5;
	public UploadResult uploadFile(HttpServletRequest request) throws IOException, FileUploadException{
		UploadResult result=new UploadResult();
		
		if(!ServletFileUpload.isMultipartContent(request)){
			result.setStatus(UploadResult.STATUS_ERR);
			result.setInfo("请选择文件。");
			return result;
		}
		//检查目录
		String fileType = request.getParameter("fileType");
		File uploadDir = new File(savePath);
		if(!uploadDir.isDirectory()){
			uploadDir.mkdir();
		}
		//检查目录写权限
		if(!uploadDir.canWrite()){
			result.setStatus(UploadResult.STATUS_ERR);
			result.setInfo("上传目录没有写权限。");
			return result;
		}

		if(!extMap.containsKey(fileType)){
			result.setStatus(UploadResult.STATUS_ERR);
			result.setInfo("不允许上传该文件类型!");
			return result;
		}
		
		//创建文件夹
			savePath += fileType + "/";
			saveUrl += fileType + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			saveUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			String fileName = item.getName();
			if (!item.isFormField()) {
				//检查文件大小
				if(item.getSize() > maxSize){
					result.setStatus(UploadResult.STATUS_ERR);
					result.setInfo("上传文件大小超过限制。");
					return result;
				}
				//检查扩展名
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				if(!Arrays.<String>asList(extMap.get(fileType).split(",")).contains(fileExt)){
					result.setStatus(UploadResult.STATUS_ERR);
					result.setInfo("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(fileType) + "格式。");
					return result;
				}

				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				try{
					//System.out.println(savePath);
					File uploadedFile = new File(savePath, newFileName);
					item.write(uploadedFile);
				}catch(Exception e){
					result.setStatus(UploadResult.STATUS_ERR);
					result.setInfo("上传文件失败。");
					return result;
				}
				result.setStatus(UploadResult.STATUS_OK);
				result.setSavePath(savePath+newFileName);
				result.setUrl(saveUrl + newFileName);
				result.setInfo("上传文件");
			}
		}
		System.out.println(result);
		return result;
	}
}
